package site.xuxingcan.sharetest;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoViewAttacher;

public class MainActivity extends AppCompatActivity {

    private PhotoViewAttacher mAttacher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        ViewGroup.LayoutParams lp = findViewById(R.id.content).getLayoutParams();
        lp.height = width;
        lp.width = width;
        findViewById(R.id.content).setLayoutParams(lp);

        ImageView mImageView = (ImageView) findViewById(R.id.image);
        mImageView.setImageResource(R.drawable.test);
        mAttacher = new PhotoViewAttacher(mImageView);
        mAttacher.update();

//        File root = new File(Environment.getExternalStorageDirectory(), "9Cut");
//        File[] files = root.listFiles();
//        ArrayList<File> newfiles = new ArrayList<>();
//        for (int i = files.length - 1; i >= 0; i--) {
//            newfiles.add(files[i]);
//        }
//        initShareIntent("com.qzone", newfiles);
    }

    private void initShareIntent(String _package, ArrayList<File> files) {
        boolean found = false;
        Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
        share.setType("image/*");
        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
        if (!resInfo.isEmpty()) {
            for (ResolveInfo info : resInfo) {
                if (info.activityInfo.packageName.toLowerCase().contains(_package) ||
                        info.activityInfo.name.toLowerCase().contains(_package)) {
                    ArrayList<Uri> imageUris = new ArrayList<Uri>();
                    for (File f : files) {
                        imageUris.add(Uri.fromFile(f));
                    }
                    share.putExtra(Intent.EXTRA_STREAM, imageUris);
                    share.setPackage(info.activityInfo.packageName);
                    found = true;
                    break;
                }
            }
            if (found) {
                startActivity(Intent.createChooser(share, "Select"));
            } else {
                Toast.makeText(this, "没有找到该应用", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
